
process.on('unhandledRejection', (reason, p) => { console.log(reason, p) })

// 正式环境的开启错误捕捉，防止进程挂掉
process.on('uncaughtException', function(err) { console.log(err) })

const { fork } = require('child_process')

process.env.NODE_ENV = 'dev'
let pc

function start() {
  console.log('重启客户端', [process.argv[2] || ''])  // --max-old-space-size=4096 
  pc = fork('test.js', [process.argv[2] || ''], { cwd: process.cwd() })
  pc.on('exit', () => {
    setTimeout(start, 500)
  })
}

start()

const fs = require('fs')
let changeTime = 0
const watchDir = (src = './') => {
  fs.watch(src, { recursive: false, interval: 100 }, () => {
    const nt = (new Date()).getTime()
    if (nt - changeTime < 1000) return // console.log((new Date).getTime() - changeTime)
    if (nt - fs.lstatSync(src).mtimeMs > 10000) return
    changeTime = (new Date()).getTime()
    pc.kill(2)
  })
}
watchDir('test.js')
